package com.axend.aerosense.main.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.axend.aerosense.base.app.AppManager;
import com.axend.aerosense.common.util.CheckUpdateUtil;
import com.blankj.utilcode.util.ToastUtils;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.gyf.immersionbar.ImmersionBar;
import com.axend.aerosense.base.activity.MvvmBaseActivity;
import com.axend.aerosense.base.impl.ILoginStatusChanged;
import com.axend.aerosense.base.livedatabus.LiveDatabus;
import com.axend.aerosense.common.adapter.ScreenAutoAdapter;
import com.axend.aerosense.common.base.IPageView;
import com.axend.aerosense.common.bean.UserInfo;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.router.RouterActivityPath;
import com.axend.aerosense.common.router.RouterFragmentPath;
import com.axend.aerosense.common.services.ILoginService;
import com.axend.aerosense.common.services.config.ServicesConfig;
import com.axend.aerosense.common.ui.CustomUpdateDialog;
import com.axend.aerosense.common.ui.NoticeDialog;
import com.axend.aerosense.main.R;
import com.axend.aerosense.main.config.TpPushConfig;
import com.axend.aerosense.main.databinding.MainActivityMainBinding;
import com.axend.aerosense.main.ui.adapter.Page2Adapter;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;


/**
 * @author ChenHongWei
 * @date :2020/12/15 17:17
 */

@Route(path = RouterActivityPath.Main.PAGE_MAIN_MAIN)
public class MainActivity extends MvvmBaseActivity<MainActivityMainBinding, MainViewModel>
    implements IPageView {
    private Fragment deviceFragment, roomFragment, homeFragment, userFragment;
    boolean firstVisable = true;
    //消息推送服务开启
    private TpPushConfig tpPushConfig;
    private Disposable disposable;
    private CustomUpdateDialog customUpdateDialog;
    private NoticeDialog noticeDialog;
    private CheckUpdateUtil checkUpdateUtil;
    private long mExitTime;
    @Autowired(name = ServicesConfig.User.LONGING_SERVICE)
    ILoginService iLoginService;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        ScreenAutoAdapter.match(this, 375.0f);
        super.onCreate(savedInstanceState);
        ARouter.getInstance().inject(this);
//        SQLiteStudioService.instance().start(this);
        tpPushConfig = new TpPushConfig(getApplicationContext());

        initView();
        init();
    }

    @Override
    protected void onResume() {
        super.onResume();
        AppManager.getInstance().addSingleActivity(this);
    }

    /**
     * 发送push token
     */
    private void sentPushToken() {
        if (null != tpPushConfig) {
            tpPushConfig.init();
        } else {
            tpPushConfig = new TpPushConfig(getApplicationContext());
            tpPushConfig.init();
        }
    }

    private void initView() {
        ImmersionBar.with(this)
                .statusBarColor(R.color.common_but_blue)
                .fitsSystemWindows(true)
                .statusBarDarkFont(true)
                .autoDarkModeEnable(true).init();

        sentPushToken();
        LiveDatabus.getInstance().with(Gobal.EVENT_KEY.USR_INFO_CHANGE, UserInfo.class)
                .observe(this, userInfo -> {
                    if (null != userFragment) {
                        ((ILoginStatusChanged) userFragment).loginStatusChanged();
                    }
                    if (null != roomFragment) {
                        ((ILoginStatusChanged) roomFragment).loginStatusChanged();
                    }
                    if (null != deviceFragment) {
                        ((ILoginStatusChanged) deviceFragment).loginStatusChanged();
                    }
                    if (null != homeFragment) {
                        ((ILoginStatusChanged) homeFragment).loginStatusChanged();
                    }
                    sentPushToken();
                });

        if (firstVisable) {
            //检查更新
            checkUpdateUtil = new CheckUpdateUtil(MainActivity.this,true);
            checkUpdateUtil.checkUpdate();
//            checkUpdate();
            firstVisable = false;
        }
    }

    private void init() {
        Page2Adapter page2Adapter = new Page2Adapter(this);
        deviceFragment = (Fragment) ARouter.getInstance().build(RouterFragmentPath.Dev.PAGE_MAIN_DEV).navigation();
        roomFragment = (Fragment) ARouter.getInstance().build(RouterFragmentPath.Room.PAGE_MAIN_ROOM).navigation();
        homeFragment = (Fragment) ARouter.getInstance().build(RouterFragmentPath.Home.PAGE_MAIN_HOME).navigation();
        userFragment = (Fragment) ARouter.getInstance().build(RouterFragmentPath.User.PAGE_MAIN_USER).navigation();

        homeFragment.getActivity();
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(homeFragment);
        fragments.add(roomFragment);
        fragments.add(deviceFragment);
        fragments.add(userFragment);
        page2Adapter.setFragments(fragments);
        viewDataBinding.mainPage.setAdapter(page2Adapter);

        //导航栏选中事件监听
        viewDataBinding.mainBtmNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int itemId = item.getItemId();
                if (itemId == R.id.nav_home) {
//                    ImmersionBar.with(MainActivity.this)
//                            .statusBarColor(android.R.color.transparent)
//                            .fitsSystemWindows(false)
//                            .statusBarDarkFont(true)
//                            .autoDarkModeEnable(true).init();
//                    setImmersionBar(0);
                    viewDataBinding.mainPage.setCurrentItem(0, true);
                } else if (itemId == R.id.nav_room) {
                    viewDataBinding.mainPage.setCurrentItem(1, true);
                } else if (itemId == R.id.nav_device) {
                    viewDataBinding.mainPage.setCurrentItem(2, true);
                } else if (itemId == R.id.nav_user) {
                    setImmersionBar(3);
                    viewDataBinding.mainPage.setCurrentItem(3, true);
                }
                return true;
            }
        });
        // 当ViewPager切换页面时，改变底部导航栏的状态
        viewDataBinding.mainPage.setOffscreenPageLimit(1);
        viewDataBinding.mainPage.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                if (0 == position) {
                    setImmersionBar(0);
                } else if (3 == position) {
                    setImmersionBar(3);
                }
                viewDataBinding.mainBtmNavigationView.getMenu().getItem(position).setChecked(true);
            }
        });

        //通知权限请求
//        NotifyUtil notifyUtil = NotifyUtil.getInstance(MainActivity.this);
//        boolean b = notifyUtil.checkNotifySetting();
//        if (!b) {
//            try {
//                CustomTitleTipsDialog dialog = new CustomTitleTipsDialog(MainActivity.this);
//                dialog.setTips(getString(R.string.main_notify_title))
//                        .setOnClickBottomListener(new CustomTitleTipsDialog.OnClickBottomListener() {
//                            @Override
//                            public void onPositiveClick() {
//                                dialog.dismiss();
//                                notifyUtil.initClickListener();
//                            }
//
//                            @Override
//                            public void onNegtiveClick() {
//                                dialog.dismiss();
//                            }
//                        })
//                        .show();
//                LogUtils.d("myTAG", "init: 通知权限还没有打开");
//            } catch (Exception e) {
//                Log.e("myTAG", "init: ", e);
//            }
//        }
    }

    /** VIP免费使用弹窗 */
//    private void showFreeVipDialog(){
//        if (freeVipDialog == null){
//            freeVipDialog = new CustomFreeVipDialog(this);
//        }
//        freeVipDialog.setOnClickBottomListener(() -> {
//            freeVipDialog.dismiss();
//        });
//        freeVipDialog.show();
//    }

    private void setImmersionBar(int index) {
        if (0 == index) {
            ImmersionBar.with(this)
                    .statusBarColor("#3578FC")
                    .fitsSystemWindows(true)
                    .statusBarDarkFont(true)
                    .autoDarkModeEnable(true).init();
        } else if (1 == index) {
            ImmersionBar.with(MainActivity.this)
                    .statusBarColor(android.R.color.transparent)
                    .navigationBarColor(R.color.black)
                    .statusBarColor(R.color.app_colorAccent)
                    .fitsSystemWindows(true)
//                            .titleBarMarginTop(R.id.topView)
                    .autoDarkModeEnable(true)
                    .init();
        } else if (2 == index) {
            ImmersionBar.with(MainActivity.this)
                    .statusBarColor(R.color.white)
                    .navigationBarColor(R.color.black)
                    .fitsSystemWindows(true)
                    .autoDarkModeEnable(true)
                    .init();
        } else if (3 == index) {
            ImmersionBar.with(MainActivity.this)
                    .statusBarColor(R.color.white)
                    .navigationBarColor(R.color.black)
                    .fitsSystemWindows(true)
                    .autoDarkModeEnable(true)
                    .init();
        }
    }

    @Override
    protected MainViewModel getViewModel() {
        return null;
    }

    @Override
    protected int getBindingVariable() {
        return 0;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.main_activity_main;
    }

    @Override
    protected void onRetryBtnClick() {

    }

    @Override
    public void onBackPressed() {
        if(getSupportFragmentManager().getBackStackEntryCount() == 0){
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                //大于2000ms则认为是误操作，使用Toast进行提示
                ToastUtils.showShort(getString(R.string.login_press_again_exit));
                //并记录下本次点击“返回键”的时刻，以便下次进行判断
                mExitTime = System.currentTimeMillis();
                return;

            } else {
                //小于2000ms则认为是用户确实希望退出程序-调用System.exit()方法进行退出
                AppManager.getInstance().AppExit();
                return;
            }
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        if(null != disposable && !disposable.isDisposed()){
            disposable.dispose();
        }
        if(null != noticeDialog && noticeDialog.isShowing()){
            noticeDialog.dismiss();
            noticeDialog = null;
        }
        if(null != customUpdateDialog && customUpdateDialog.isShowing()){
            customUpdateDialog.dismiss();
            customUpdateDialog = null;
        }
        super.onDestroy();
//        SQLiteStudioService.instance().stop();
    }
    @Override
    public void setViewPageScolleEnabled(boolean enabled){
        viewDataBinding.mainPage.setUserInputEnabled(enabled);
    }

    //检查更新已抽离成工具类
//    public void checkUpdate(){
//        disposable = EasyHttp.post(UrlApi.URL.GetAppVersion.getUrl())
//                .cacheMode(CacheMode.NO_CACHE)
//                .upJson(JsonUtil.toJson(new BaseDevInfoBean()))
//                .execute(new SimpleCallBack<UpdateAppBean>() {
//                    @Override
//                    public void onTokenExpire() {
//
//                    }
//
//                    @Override
//                    public void onError(ApiException e) {
//                        e.printStackTrace();
//                    }
//
//                    @Override
//                    public void onSuccess(UpdateAppBean updateAppBean) {
//                        String versionCode = "" + EquipmentUtil.getAppVersionNumber();
//                        // 需要更新提示的 1. 客户端版本和服务器端不一致, 2.强制更新的, 3. 可跳过的版本号和已经跳过的版本号不一致
//                        if(!TextUtils.isEmpty(updateAppBean.getServiceEdtion()) && !versionCode.equals(updateAppBean.getServiceEdtion()) ){
//                            String lastVersionCode = "" + MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.LAST_JUMP_VERSION, "");
//                            if(updateAppBean.getState() == 0 && lastVersionCode.equals(updateAppBean.getServiceEdtion())){
//                                //3. 可跳过的版本号和已经跳过的版本号一致无需提示
//                                getNotice();
//                                return;
//                            }
//                            try {
//                                if (TextUtils.isEmpty(updateAppBean.getServiceEdtion())
//                                        || Integer.parseInt(versionCode) >= Integer.parseInt(updateAppBean.getServiceEdtion())){
//                                    getNotice();
//                                    return;
//                                }
//                            }catch (Exception e){
//                                e.printStackTrace();
//                            }
//
//                            customUpdateDialog = new CustomUpdateDialog(MainActivity.this, updateAppBean, false);
//                            customUpdateDialog.setCancelable(false);
//                            customUpdateDialog.setCanceledOnTouchOutside(false);
//
//                            customUpdateDialog.setOnClickBottomListener(new CustomUpdateDialog.OnClickBottomListener() {
//                                @Override
//                                public void onPositiveClick() {
//
//                                }
//
//                                @Override
//                                public void onNegtiveClick() {
//                                    if(updateAppBean.getState() == 0){
//                                        MmkvHelper.getInstance().getMmkv().encode(Gobal.SAVE_KEY.LAST_JUMP_VERSION, updateAppBean.getServiceEdtion());
//                                        getNotice();
//                                    }
//
//                                }
//
//                                @Override
//                                public void onCloseClick() {
//                                    if(updateAppBean.getState() == 0){
//                                        MmkvHelper.getInstance().getMmkv().encode(Gobal.SAVE_KEY.LAST_JUMP_VERSION, updateAppBean.getServiceEdtion());
//                                        getNotice();
//                                    }
//                                }
//                            });
//                            customUpdateDialog.show();
//                        }else{
//                            getNotice();
//                        }
//                    }
//                });
//    }
//
//    public void getNotice(){
//        String token = MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.TOKEN);
//        if(TextUtils.isEmpty(token)){
//            return;
//        }
//        disposable = EasyHttp.post(UrlApi.URL.GetNotice.getUrl())
//                .cacheMode(CacheMode.NO_CACHE)
//                .headers("token", token)
//                .upJson(JsonUtil.toJson(new BaseDevInfoBean()))
//                .execute(new SimpleCallBack<NoticeBean>() {
//                    @Override
//                    public void onTokenExpire() {
//
//                    }
//
//                    @Override
//                    public void onError(ApiException e) {
//                        e.printStackTrace();
//                    }
//
//                    @Override
//                    public void onSuccess(NoticeBean noticeBean) {
//                        UserInfo userInfo = MmkvHelper.getInstance().getMmkv().decodeParcelable(Gobal.SAVE_KEY.USR_INFO, UserInfo.class);
//                        if(null != userInfo && userInfo.userVipState != 1){
//                            // 非VIP 才弹出 广告
//                            noticeDialog = new NoticeDialog(MainActivity.this, noticeBean);
//                            MainActivity.this.noticeBean = noticeBean;
//                            noticeDialog.setCancelable(false);
//                            noticeDialog.setCanceledOnTouchOutside(false);
//                            noticeDialog.setOnClickBottomListener(listener);
//                            noticeDialog.show();
//                        }
//                    }
//                });
//    }
//
//    private NoticeBean noticeBean;
//
//    private NoticeDialog.OnClickBottomListener listener = new NoticeDialog.OnClickBottomListener() {
//
//        @Override
//        public void onPositiveClick() {
//            if(null == noticeBean){
//                return;
//            }
//            if(noticeBean.noticeType == 0){
//                iLoginService.logout(MainActivity.this, () -> {
//                    iLoginService.login();
//                    finish();
//                });
//            }else{
//                Intent intent = new Intent(MainActivity.this, WebActivity.class);
//                intent.putExtra(WebActivity.URL, (String) noticeBean.noticeUrl);
//                startActivity(intent);
//            }
//
//        }
//
//        @Override
//        public void onCloseClick() {
//
//        }
//    };

}
